package com.wyh.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        initFlowRules();
        for (int i = 0; i < 20; i++) {
            test(i);
        }
    }

    private static void test(int i) {
        try(Entry entry = SphU.entry("resourceName")){
//业务逻辑处理
            System.out.println("执⾏test⽅法"+ i);
        } catch (BlockException e) {
//处理限流时的逻辑
            System.out.println("触发限流.." +i );
        }
    }

    public static void main1(String[] args) {
        // 配置规则.
        initFlowRules();

        while (true) {
            // 1.5.0 版本开始可以直接利用 try-with-resources 特性
            try (Entry entry = SphU.entry("HelloWorld")) {
                // 被保护的逻辑
                System.out.println("hello world");
            } catch (BlockException ex) {
                // 处理被流控的逻辑
                System.out.println("blocked!");
            }
//            try {
//                Thread.sleep(500); // 每 500 毫秒执行一次，控制 QPS 在 2 左右
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("resourceName");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(10);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

}
